<template>
  <div class="main">
    <nav-bar class="home-nav">
      <div class="left" slot="left" @click="goBack">
        <van-icon name="arrow-left" size="24"/>
      </div>
      <div slot="center">打印机管理</div>
    </nav-bar>

    <div class="blue_box">
      <van-button plain type="info" @click="searchBle" block >搜索蓝牙</van-button>
      <div class="lists" :key="index" v-for="(item,index) in devices">
        <span @click="onConn(item)">{{item.name}}</span>
      </div>
      <div class="linked">
        <div class="title2">已连接设备：</div>
        <span>{{currDevName}}</span>
      </div>

      <van-button v-if="this.connId != ''" plain type="info" @click="destroyed" block >断开连接</van-button>
    </div>



  </div>

</template>

<script>

  // var tsc = require('@/components/print/tsc.js')
  //  var esc = require('@/components/print/esc.js')
  import Util from "@/common/util";
  import NavBar from "@/components/common/navbar/NavBar"

  export default {
    data() {
      return {
        devices: [],
        currDev: null,
        currDevName:'无',
        connId: '',
      }
    },
    components: {
      NavBar
    },

    created() {
      this.initBle();
      let currDevName = Util.storage.get('currDevName');
      if(currDevName != ''){
        this.currDevName = currDevName
      }

      let mac_adress = Util.storage.get('mac_adress');
      console.log('mac_adress'+JSON.stringify(mac_adress))
      if(mac_adress != ''){
        this.connId = mac_adress
      }
    },

    methods: {
      goBack() {
        this.$router.go(-1);
      },

      destroyed: function () {
        let that =this;
        console.log(JSON.stringify(this.connId))
        console.log("destroyed----------")
        if (this.connId != '') {
          plus.bluetooth.closeBLEConnection({
            deviceId: that.connId,
            success(res) {
              Util.storage.set('mac_adress','')
              Util.storage.set('currDevName','无')
              Util.storage.set('currDev','')
              console.log(res)
              that.currDevName = "无"
              this.$toast('断开成功')
            },
            fail:function(e){
              console.log('close failed: '+JSON.stringify(e));
            }
          })
        }
      },

      initBle(){
        plus.bluetooth.openBluetoothAdapter({
          success(res) {
            console.log("打开 蓝牙模块")
            console.log(res)
          }
        })
      },

      searchBle() {
        var that = this
        console.log("initBule")
        plus.bluetooth.openBluetoothAdapter({
          success(res) {
            console.log("打开 蓝牙模块")
            console.log(res)
            that.onDevice()
            plus.bluetooth.getBluetoothAdapterState({
              success: function (res) {
                console.log(res)
                if (res.available) {
                  if (res.discovering) {
                    that.stopFindBule()
                  }
                  //搜索蓝牙
                  //开始搜寻附近的蓝牙外围设备
                  console.log("开始搜寻附近的蓝牙外围设备")
                  plus.bluetooth.startBluetoothDevicesDiscovery({
                    success(res) {
                      console.log(res)
                    }
                  })

                } else {
                  console.log('本机蓝牙不可用')
                }
              },
            })
          }
        })
      },
      onDevice() {
        console.log("监听寻找到新设备的事件---------------")
        var that = this
        //监听寻找到新设备的事件
        plus.bluetooth.onBluetoothDeviceFound(function (devices) {
          console.log('--------------new-----------------------' + JSON.stringify(devices))
          var re = JSON.parse(JSON.stringify(devices))
          console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
          let name = re.devices[0].name
          if (name != "") {
            let deviceId = re.devices[0].deviceId;
            that.devices.push({
              name: name,
              deviceId: deviceId,
              services: []
            })
          }
        })
      },

      stopFindBule() {
        console.log("停止搜寻附近的蓝牙外围设备---------------")
        plus.bluetooth.stopBluetoothDevicesDiscovery({
          success(res) {
            console.log(res)
          }
        })
      },

      onConn(item) {
        var that = this
        console.log("连接蓝牙---------------" + item.deviceId)
        this.$toast({
          message: '连接中',
        });
        let deviceId = item.deviceId
        plus.bluetooth.createBLEConnection({
          deviceId: deviceId,
          timeout: 5000,
          success: function (res) {
            console.log('create connection success: ' + JSON.stringify(res));
          },
          fail: function (e) {
            console.log('create connection failed: ' + JSON.stringify(e));
          },
          complete(res) {
            console.log('create connection complete: ' + JSON.stringify(res));
            if (res.message == "ok") {
              that.$toast.clear();
              that.$toast('连接成功')
              Util.storage.set('mac_adress',deviceId)
              Util.storage.set('currDevName',item.name)
              console.log("连接蓝牙-[" + item.name + "]--成功")
              that.connId = deviceId;
              that.currDevName = item.name;
              //that.currDev = item


              setTimeout(function () {
                that.getBLEServices(deviceId)
              }, 3000)

            } else {
              console.log(res)
            }
            //连接成功 关闭搜索
            that.stopFindBule()

          },
        })
      },

      getBLEServices(_deviceId) {
        var that = this;
        let deviceId = _deviceId
        console.log("获取蓝牙设备所有服务(service)。---------------")

        plus.bluetooth.getBLEDeviceServices({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          deviceId: deviceId,
          complete(res) {
            console.log('服务'+JSON.stringify(res))
            let serviceId = ""

            for (var s = 0; s < res.services.length; s++) {
              console.log('每个服务'+res.services[s].uuid)
              let serviceId = res.services[s].uuid
              plus.bluetooth.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                deviceId: deviceId,
                // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                serviceId: serviceId,
                success(res) {
                  console.log('每个特征值'+JSON.stringify(res))
                  var re = JSON.parse(JSON.stringify(res))
                  console.log('deviceId = [' + deviceId + ']  serviceId = [' + serviceId + ']')
                  for (var c = 0; c < re.characteristics.length; c++) {
                    if (re.characteristics[c].properties.write == true) {
                      let uuid = re.characteristics[c].uuid
                      console.log(' deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +
                        uuid)

                      for (var index in that.devices) {
                        if (that.devices[index].deviceId == deviceId) {
                          that.devices[index].services.push({
                            serviceId: serviceId,
                            characteristicId: uuid
                          })
                          console.log('测试某个设备:'+JSON.stringify(that.devices[index]))
                          Util.storage.set('currDev',that.devices[index])
                          break
                        }
                      }
                      console.log('测试devices:'+JSON.stringify(that.devices))

                    }
                  }
                }
              })
            }
          },
          fail(res) {
            console.log(res)
          },
        })
      },

      senBlData(deviceId, serviceId, characteristicId, uint8Array) {
        console.log('打印时：deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' + characteristicId + "]")
        var uint8Buf = Array.from(uint8Array);

        function split_array(datas, size) {
          var result = {};
          var j = 0
          for (var i = 0; i < datas.length; i += size) {
            result[j] = datas.slice(i, i + size)
            j++
          }
          console.log(result)
          return result
        }

        var sendloop = split_array(uint8Buf, 20);

        // console.log(sendloop.length)
        function realWriteData(sendloop, i) {
          var data = sendloop[i]
          console.log('00写入第：'+JSON.stringify(i))
          console.log(typeof (data))
          if (typeof (data) == "undefined") {
            return
          }
          console.log("第【" + i + "】次写数据" + data)
          var buffer = new ArrayBuffer(data.length)
          var dataView = new DataView(buffer)
          for (var j = 0; j < data.length; j++) {
            dataView.setUint8(j, data[j]);
          }
          plus.bluetooth.writeBLECharacteristicValue({
            deviceId,
            serviceId,
            characteristicId,
            value: buffer,
            success(res) {
              realWriteData(sendloop, i + 1);
            }
          })
        }

        var i = 0;
        realWriteData(sendloop, i);
      },

      senBleLabel() {
        //标签模式
        let deviceId = this.currDev.deviceId;
        let serviceId = this.currDev.services[0].serviceId;
        let characteristicId = this.currDev.services[0].characteristicId;
        var command = tsc.jpPrinter.createNew()
        command.setSize(40, 30)
        command.setGap(2)
        command.setCls()
        command.setText(50, 10, "TSS24.BF2", 1, 1, "打印测试")
        command.setQR(50, 50, "L", 6, "A", "https://fanyi.baidu.com/")
        command.setPagePrint()
        this.senBlData(deviceId, serviceId, characteristicId, command.getData())
      },
    }
  }
</script>

<style>
  .blue_box{
    margin: 10px 15px;
  }
  .lists{
    padding: 10px 0;
    font-size: .32rem;
  }
  .linked{
    margin: 30px 0;
    font-size: .32rem;
  }
  .title2{
    padding-bottom: 10px;
  }
</style>
